package com.fire.chat.init;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.PostConstruct;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @program: hxzq
 * @description: 全局系统初始化执行器
 * @author: xjr
 * @create: 2020-11-04 15:06
 **/
@Configuration
@Slf4j
public class SystemInitializationRunner implements CommandLineRunner {
    @Autowired
    @Qualifier("taskExecutor")
    private ThreadPoolTaskExecutor executorService;

    @Autowired(required = false)
    List<AsyncAppStartEvent> asyncAppStartEvents;


    private static  CountDownLatch COUNT_DOWN_LATCH;

    @PostConstruct
    public void init(){
        if (CollectionUtils.isNotEmpty(asyncAppStartEvents)){
            COUNT_DOWN_LATCH=new CountDownLatch(asyncAppStartEvents.size());
        }
    }


    @Override
    public void run(String... args)  {
        if (CollectionUtils.isNotEmpty(asyncAppStartEvents)){
            executorService.execute(()->{
                log.info("------------------------------------------开始执行全局初始化任务-----------------------------------------");
                this.asyncAppStartEvents.stream()
                        .sorted(Comparator.comparing(AsyncAppStartEvent::order))
                        .peek(data->{
                            data.setCount(COUNT_DOWN_LATCH);
                        })
                        .forEach(executorService::execute);
                try {
                    COUNT_DOWN_LATCH.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info("------------------------------------------全局初始化任务执行结束-----------------------------------------");

            });
        }


    }



}
